import { Animation, _decorator } from "cc";
import { ENTITY_STATE_ENUM, PARAM_NAME_ENUM } from "../../Enums";
import StateMachine, { getInitParamsNumber, getInitParamTrigger } from "../../Base/StateMachine";
import IdleSubStateMachine from "./IdleSubStateMachine";
import DeathSubStateMachine from "./DeathSubStateMachine";
import { EntityManager } from "../../Base/EntityManager";

const {ccclass, property} = _decorator

@ccclass('SmokeStateMachine')
export class SmokeStateMachine extends StateMachine {
  async init() {
    this.animationComponent = this.addComponent(Animation)
    this.initParams()
    this.initStateMachines()
    this.initAnimationEvent()

    await Promise.all(this.waitingList)
  }
  initAnimationEvent() {
    this.animationComponent.on(Animation.EventType.FINISHED, () => {
      const name = this.animationComponent.defaultClip.name
      const whileList = ['idle']
      if (whileList.some(v => name.includes(v))) {
        this.node.getComponent(EntityManager).state = ENTITY_STATE_ENUM.DEATH
      }
    })
  }
  initStateMachines() {
    this.stateMachines.set(PARAM_NAME_ENUM.IDLE, new IdleSubStateMachine(this))
    this.stateMachines.set(PARAM_NAME_ENUM.DEATH, new DeathSubStateMachine(this))
  }

  initParams() {
    this.params.set(PARAM_NAME_ENUM.IDLE, getInitParamTrigger())
    this.params.set(PARAM_NAME_ENUM.DIRECTION, getInitParamsNumber())
    this.params.set(PARAM_NAME_ENUM.DEATH, getInitParamTrigger())
  }

  run() {
    switch (this.currentState) {
      case this.stateMachines.get(PARAM_NAME_ENUM.IDLE):
      case this.stateMachines.get(PARAM_NAME_ENUM.DEATH):
        if (this.params.get(PARAM_NAME_ENUM.DEATH).value) {
          this.currentState = this.stateMachines.get(PARAM_NAME_ENUM.DEATH)
        } else if (this.params.get(PARAM_NAME_ENUM.IDLE).value) {
          this.currentState = this.stateMachines.get(PARAM_NAME_ENUM.IDLE)
        } else {
          this.currentState = this.currentState
        }
        break
      default:
        this.currentState = this.stateMachines.get(PARAM_NAME_ENUM.IDLE)
    }
  }
}

